﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using DungChung;
using System.Windows.Threading;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.Windows.Media.Effects;
namespace CoVuaClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        bool dangTrongTranDau;
        BanCo banCo;
        Image[,] images;
        int chiSoCotDaChon;
        int chiSoDongDaChon;
        bool luotCuaToi;
        string ipServer;
        public MainWindow()
        {
            InitializeComponent();
            CoNguoiDangNhap += new EventHandler(MainWindow_CoNguoiDangNhap);
            CoNguoiDangXuat += new EventHandler(MainWindow_CoNguoiDangXuat);
            CoNguoiThayDoiTrangThai += new EventHandler(MainWindow_CoNguoiThayDoiTrangThai);
            timer = new DispatcherTimer();
            timer.Tick += new EventHandler(dispatcherTimer_Tick);
            timer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
            dangTrongTranDau = false;
            banCo = new BanCo();
            ThayDoiTrenBanCo += new EventHandler(MainWindow_ThayDoiTrenBanCo);
            images = new Image[8,8];
            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    images[i, j] = new Image();
                    images[i, j].Height = 79;
                    images[i, j].Width = 79;
                    images[i, j].MouseLeftButtonUp += new MouseButtonEventHandler(SuKienAnChuot);
                    images[i, j].MouseEnter += new MouseEventHandler(MainWindow_MouseEnter);
                    images[i, j].MouseLeave += new MouseEventHandler(MainWindow_MouseLeave);
                }
            }
            UpdateControl();
            chiSoCotDaChon = -1;
            chiSoDongDaChon = -1;
        }
        DispatcherTimer timer;
        QuanLiKetNoiClient quanLiKetNoi;
        public event EventHandler CoNguoiDangNhap;
        public event EventHandler CoNguoiDangXuat;
        public event EventHandler CoNguoiThayDoiTrangThai;
        public event EventHandler ThayDoiTrenBanCo;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ipServer = findIPServer();
            if (ipServer != "")
            {
                DangNhapAndAfter();
                imageAnhBan.Source = new BitmapImage(new Uri(@"/CoVuaClient;component/Pic/KnightYellow.png", UriKind.RelativeOrAbsolute));
            }
            else
            {
                MessageBox.Show(this, "Không thể kết nối tới server!");
                this.Close();
            }
            
        }

        private void DangNhapAndAfter()
        {
            DangNhapWindow dangNhap = new DangNhapWindow();
            dangNhap.ipServer = ipServer;
            dangNhap.Owner = this;
            dangNhap.ShowDialog();
            if (dangNhap.tcpClient != null )
            {
                quanLiKetNoi = new QuanLiKetNoiClient(dangNhap.tcpClient);
                quanLiKetNoi.ShowItem.CollectionChanged += new NotifyCollectionChangedEventHandler(ShowItem_CollectionChanged);
                dangNhap.Close();

                labelTaiKhoan.Text = quanLiKetNoi.TaiKhoan.TenHienThi;
                labelGioiThieu.Text = "Giới thiệu: " + quanLiKetNoi.TaiKhoan.GioiThieu;
                labelKinhNghiem.Text = "Kinh nghiệm: " + quanLiKetNoi.TaiKhoan.KinhNghiem.ToString("000000");
                labelStatus.Text = "Status: " + quanLiKetNoi.TaiKhoan.Status;

                string packetInfo = quanLiKetNoi.RecievePacketInfo();
                quanLiKetNoi.ReceiveListUser();
                timer.Start();
            }           
        }



        private void ListBoxDanhSachNguoiChoi_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ListBoxDanhSachNguoiChoi.SelectedItem != null)
            {
                Item item = (Item)ListBoxDanhSachNguoiChoi.SelectedItem;
                if ( MessageBoxResult.OK == MessageBox.Show(this, "Bạn có chắc mời " + item.TenHienThi + " tham gia trận đấu không?",
                    "Gửi lời mời!",
                    MessageBoxButton.OKCancel, MessageBoxImage.Question))
                {
                    quanLiKetNoi.GuiLoiMoi(item.Username);
                }             
            }          
        }

        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Logout_Click(object sender, RoutedEventArgs e)
        {
            timer.Stop();
            if (quanLiKetNoi != null)
            {
                quanLiKetNoi.DongKetNoi();
                ListBoxDanhSachNguoiChoi.ItemsSource = null;
                DangNhapAndAfter();
            }
        }


        public void ShowItem_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            ListBoxDanhSachNguoiChoi.ItemsSource = null;
            ListBoxDanhSachNguoiChoi.ItemsSource = quanLiKetNoi.ShowItem;
        }
        public void ChatShowList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            listBoxChat.ItemsSource = null;
            listBoxChat.ItemsSource = quanLiKetNoi.ChatShowList;
        }
        public void MainWindow_CoNguoiDangNhap(object sender, EventArgs e)
        {
            Item item;
            item = new Item();
            item = quanLiKetNoi.RecieveUserInfo();
            item.ThuTu = (quanLiKetNoi.ShowItem.Count + 1).ToString("00");
            quanLiKetNoi.ShowItem.Add(item);
        }
        public void MainWindow_CoNguoiThayDoiTrangThai(object sender, EventArgs e)
        {
            ListBoxDanhSachNguoiChoi.ItemsSource = null;
            ListBoxDanhSachNguoiChoi.ItemsSource = quanLiKetNoi.ShowItem;
        }
        public void MainWindow_CoNguoiDangXuat(object sender, EventArgs e)
        {
            Item taiKhoan;
            taiKhoan = new Item();
            taiKhoan = quanLiKetNoi.RecieveUserInfo();
            int point = -1;
            for (int i = 0; i < quanLiKetNoi.ShowItem.Count; i++)
            {
                if (quanLiKetNoi.ShowItem[i].Username == taiKhoan.Username)
                {
                    point = i;
                }
            }
            quanLiKetNoi.ShowItem.RemoveAt(point);
        }

        public void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                string packetInfo = quanLiKetNoi.RecievePacketInfo();
                if (packetInfo == MyTask.CoNguoiDangNhap)
                {
                    CoNguoiDangNhap(null, null);
                }
                if (packetInfo == MyTask.CoNguoiDangXuat)
                {
                    CoNguoiDangXuat(null, null);
                }
                if (packetInfo == MyTask.LoiMoiThamGiaVanDau)
                {
                    #region Xu li loi cua nguoi choi khac
                    string username = quanLiKetNoi.RecievePacketInfo();
                    if (MessageBoxResult.OK == MessageBox.Show(this, "Người chơi " + quanLiKetNoi.RecievePacketInfo() +
                        " muốn mời bạn tham gia trận đấu!",
                    "Lời mời tham gia trận đấu!",
                    MessageBoxButton.OKCancel, MessageBoxImage.Question))
                    {
                        quanLiKetNoi.NhanLoiMoi(username);
                        for (int i = 0; i < quanLiKetNoi.ShowItem.Count; i++)
                        {
                            if (quanLiKetNoi.ShowItem[i].Username == username)
                            {
                                quanLiKetNoi.ShowItem[i].UserState = "Đã có người chơi cùng rồi!";
                                CoNguoiThayDoiTrangThai(null,null);
                            }
                        }
                        dangTrongTranDau = true;
                        banCo.DatQuanCoLenBanCo();
                        ThayDoiTrenBanCo(null, null);
                        quanLiKetNoi.ChatShowList.CollectionChanged += 
                            new NotifyCollectionChangedEventHandler(ChatShowList_CollectionChanged);
                        luotCuaToi = false;
                    
                    }
                    else
                    {
                        quanLiKetNoi.TuChoiLoiMoi(username);
                    }
                    #endregion
                }
                if (packetInfo == MyTask.NhanLoiMoi)
                {
                    #region Xu li su kien doi phuong nhan loi moi
                    string username = quanLiKetNoi.RecievePacketInfo();
                    for (int i = 0; i < quanLiKetNoi.ShowItem.Count; i++)
                    {
                        if (quanLiKetNoi.ShowItem[i].Username == username)
                        {
                            quanLiKetNoi.ShowItem[i].UserState = "Đã có người chơi cùng rồi!";
                            CoNguoiThayDoiTrangThai(null, null);
                        }
                    }
                    luotCuaToi = true;
                    dangTrongTranDau = true;
                    banCo.DatQuanCoLenBanCo();
                    ThayDoiTrenBanCo(null, null);
                    quanLiKetNoi.ChatShowList.CollectionChanged += new NotifyCollectionChangedEventHandler(ChatShowList_CollectionChanged);
                    #endregion
                }
                if (packetInfo == MyTask.TuChoi)
                {
                    MessageBox.Show(this,packetInfo);
                }
                if (packetInfo == MyTask.NguoiChoiDangBan)
                {
                    string mess = string.Format("Người chơi {0} đang bận",quanLiKetNoi.RecievePacketInfo());
                    MessageBox.Show(this, mess);
                }
                if (packetInfo == MyTask.CoNguoiTaoMoiTranDau)
                {
                    #region Xu li Thay doi trang thai
                    string user1 = quanLiKetNoi.RecievePacketInfo();
                    string user2 = quanLiKetNoi.RecievePacketInfo();
                    foreach (var item in quanLiKetNoi.ShowItem)
                    {
                        if (item.Username == user1 || item.Username == user2)
                        {
                            item.UserState = "Đã có người chơi cùng rồi!";
                            CoNguoiThayDoiTrangThai(null, null);
                        }
                    }
                    #endregion
                }
                if (packetInfo == MyTask.Chat)
                {
                    #region Xu li tin nhan chat
                    if (dangTrongTranDau)
                    {
                        ChatItem item = new ChatItem();
                        item.NguoiGui = quanLiKetNoi.RecievePacketInfo();
                        item.NoiDung = quanLiKetNoi.RecievePacketInfo();
                        quanLiKetNoi.ChatShowList.Add(item);
                    }
                    #endregion
                }
                if (packetInfo == MyTask.XinThua)
                {
                    ResetBanCo();
                }
                if (packetInfo == MyTask.NuocDi)
                {
                    #region Xu li Nuoc di cua doi phuong
                    int CotDi = 7 - quanLiKetNoi.Reader.ReadInt32();
                    int DongDi = 7 - quanLiKetNoi.Reader.ReadInt32();
                    int CotDen = 7 - quanLiKetNoi.Reader.ReadInt32();
                    int DongDen = 7 - quanLiKetNoi.Reader.ReadInt32();
                    QuanCo quanCo;
                    quanCo = banCo.DiChuyenQuanCo(CotDi, DongDi, CotDen, DongDen);
                    if (quanCo != null)
                    {
                        Image imageMinh = new Image();
                        imageMinh.Source = new BitmapImage(new Uri(quanCo.PathImage, UriKind.RelativeOrAbsolute));
                        imageMinh.ToolTip = quanCo.TenQuanCo;
                        imageMinh.Height = 30;
                        imageMinh.Width = 30;
                        if (stackMinh1.Children.Count < 8)
                        {
                            stackMinh1.Children.Add(imageMinh);
                        }
                        else
                        {
                            stackminh2.Children.Add(imageMinh);
                        }
                    }
                    if (quanLiKetNoi.Reader.ReadBoolean())
                    {
                        MessageBox.Show(this, "Chiếu tướng!");
                    }
                    luotCuaToi = !luotCuaToi;
                    ThayDoiTrenBanCo(null, null);
                    #endregion
                }
                if (packetInfo == MyTask.ChienThang)
                {
                    labelKinhNghiem.Text = quanLiKetNoi.Reader.ReadInt32().ToString("000000");
                    MessageBox.Show(this, "Bạn đã thua!");
                    ResetBanCo();
                }
            }
            catch (IOException)
            {
            }
            
        }

        private void ResetBanCo()
        {
            dangTrongTranDau = false;
            banCo = new BanCo();
            ThayDoiTrenBanCo(null, null);
            stackDoiPhuong1.Children.Clear();
            stackDoiPhuong2.Children.Clear();
            stackMinh1.Children.Clear();
            stackminh2.Children.Clear();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
        }

        

        private void ButtonSend_Click(object sender, RoutedEventArgs e)
        {
            if (dangTrongTranDau == true)
            {
                quanLiKetNoi.GuiTinNhanChat(TextBoxChat.Text);
                ChatItem chatItem = new ChatItem();
                chatItem.NguoiGui = "Tôi";
                chatItem.NoiDung = TextBoxChat.Text;
                quanLiKetNoi.ChatShowList.Add(chatItem);
                TextBoxChat.Text = string.Empty;
            }
        }

        private void AboutMe_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void ListDSCaoDiem_Click(object sender, RoutedEventArgs e)
        {
            if (quanLiKetNoi != null)
            {
                XemDachSachNguoiChoiCaoDiem frm = new XemDachSachNguoiChoiCaoDiem(quanLiKetNoi.Client, quanLiKetNoi.Stream);
                frm.Owner = this;
                frm.ShowDialog();
            }
            else
            {
                if (MessageBox.Show(this, "Bạn chưa đăng nhập!\nBạn có muốn đăng nhập không?") == MessageBoxResult.OK)
                {
                    DangNhapAndAfter();
                }
                
            }
        }
        private void MainWindow_ThayDoiTrenBanCo(object sender, EventArgs e)
        {
            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    images[i, j].Source = null;
                    if (banCo.DsOCo[i,j].QuanCoHienTai != null)
                    {
                        images[i, j].ToolTip = banCo.DsOCo[i, j].QuanCoHienTai.TenQuanCo;
                        images[i, j].Source = new BitmapImage(new Uri(banCo.DsOCo[i, j].QuanCoHienTai.PathImage,
                            UriKind.RelativeOrAbsolute));
                    }
                    else
                    {
                        images[i, j].Source = new BitmapImage(new Uri(banCo.DsOCo[i, j].ImagePath,
                            UriKind.RelativeOrAbsolute));
                    }
                }
            }
        }
        public void UpdateControl()
        {           
            for (int j = 0; j < 8; j++)
            {
                Stack1.Children.Add(images[0,j]);
            }
            for (int j = 0; j < 8; j++)
            {
                Stack2.Children.Add(images[1, j]);
            }
            for (int j = 0; j < 8; j++)
            {
                Stack3.Children.Add(images[2, j]);
            }
            for (int j = 0; j < 8; j++)
            {
                Stack4.Children.Add(images[3, j]);
            }
            for (int j = 0; j < 8; j++)
            {
                Stack5.Children.Add(images[4, j]);
            }
            for (int j = 0; j < 8; j++)
            {
                Stack6.Children.Add(images[5, j]);
            }
            for (int j = 0; j < 8; j++)
            {
                Stack7.Children.Add(images[6, j]);
            }
            for (int j = 0; j < 8; j++)
            {
                Stack8.Children.Add(images[7, j]);
            }
            
        }

        public void MainWindow_MouseEnter(object sender, MouseEventArgs e)
        {
            BlurEffect blurEffect = new BlurEffect();
            blurEffect.Radius = 3;
            ((Image)sender).Effect = blurEffect;
        }
        public void MainWindow_MouseLeave(object sender, MouseEventArgs e)
        {
            BlurEffect blurEffect = new BlurEffect();
            blurEffect.Radius = 0;
            ((Image)sender).Effect = blurEffect;
        }
        public void SuKienAnChuot(object sender, MouseButtonEventArgs e)
        {
            if (chiSoCotDaChon != -1)
            {
                #region Tim ra Chi So Cua OCo Dang chon
                Image image = (Image)sender;
                int chiSoDong = 0;
                int chiSoCot = 0;
                for (int i = 0; i < 8; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        if (image == images[i, j])
                        {
                            chiSoCot = i;
                            chiSoDong = j;
                        }
                    }
                }
                #endregion
                if (banCo.DsOCo[chiSoCotDaChon, chiSoDongDaChon].QuanCoHienTai != null)
                {
                    #region Xu li o da cho co quan co
                    if (banCo.DsOCo[chiSoCotDaChon, chiSoDongDaChon].QuanCoHienTai.PheMinh)                     // O chọn trước là phe mình
                    {                                                                                           // thì kiểm tra có được di 
                        if (banCo.KiemTraCoDiChuyenKo(chiSoCotDaChon, chiSoDongDaChon, chiSoCot, chiSoDong))    // chuyen ko. Neu duoc thi
                        {                                                                                       // cho quan co di chuyen
                            if (luotCuaToi)
                            {
                                QuanCo quanCo;
                                quanCo = banCo.DiChuyenQuanCo(chiSoCotDaChon, chiSoDongDaChon, chiSoCot, chiSoDong);
                                bool chieuTuong;
                                chieuTuong = banCo.KiemTraChieuTuong(chiSoCot, chiSoDong);
                                quanLiKetNoi.SendNuocDi(chiSoCotDaChon, chiSoDongDaChon, chiSoCot, chiSoDong, chieuTuong);
                                if (quanCo != null)
                                {
                                    if (quanCo.TenQuanCo == "Vua")
                                    {
                                        labelKinhNghiem.Text = quanLiKetNoi.ChienThang().ToString("000000");
                                        MessageBox.Show(this, "Chúc mừng bạn đã giành chiến thắng!");
                                        ResetBanCo();
                                    }
                                    else
                                    {
                                        Image imageA = new Image();
                                        imageA.Height = 30;
                                        imageA.Width = 30;
                                        imageA.ToolTip = quanCo.TenQuanCo;
                                        imageA.Source = new BitmapImage(new Uri(quanCo.PathImage, UriKind.RelativeOrAbsolute));
                                        if (stackDoiPhuong2.Children.Count < 8)
                                        {
                                            stackDoiPhuong2.Children.Add(imageA);
                                        }
                                        else
                                        {
                                            stackDoiPhuong1.Children.Add(imageA);
                                        }
                                    }
                                    
                                }
                                chiSoCotDaChon = chiSoCot;
                                chiSoDongDaChon = chiSoDong;                              
                                luotCuaToi = !luotCuaToi;
                            }
                            
                        }
                        else
                        {                                                                                       // O chon truoc la phe minh
                            if (banCo.DsOCo[chiSoCot,chiSoDong].QuanCoHienTai != null)                          // nhung khong the di
                            {                                                                                   // duoc. kiem tra o moi vua
                                if (banCo.DsOCo[chiSoCot,chiSoDong].QuanCoHienTai.PheMinh)                      // chon co phai phe minh ko
                                {
                                    banCo.DsOCo[chiSoCotDaChon,chiSoDongDaChon].QuanCoHienTai.ChangeState();
                                    banCo.DsOCo[chiSoCot,chiSoDong].QuanCoHienTai.ChangeState();
                                    chiSoCotDaChon = chiSoCot;
                                    chiSoDongDaChon = chiSoDong; 
                                }                                                                              
                            }
                        }
                    
                    }
                    else
                    {
                        if (banCo.DsOCo[chiSoCot, chiSoDong].QuanCoHienTai != null)                          // nhung khong the di
                        {                                                                                   // duoc. kiem tra o moi vua
                            if (banCo.DsOCo[chiSoCot, chiSoDong].QuanCoHienTai.PheMinh)                      // chon co phai phe minh ko
                            {
                                banCo.DsOCo[chiSoCot, chiSoDong].QuanCoHienTai.ChangeState();
                                chiSoCotDaChon = chiSoCot;
                                chiSoDongDaChon = chiSoDong; 
                            }
                        }
                    }
                    #endregion

                }
                
                           
            }
            else
            {
                #region Xu li su kien chon dau tien
                Image image = (Image)sender;
                int chiSoDong = 0;
                int chiSoCot = 0;
                for (int i = 0; i < 8; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        if (image == images[i, j])
                        {
                            chiSoCot = i;
                            chiSoDong = j;
                        }
                    }
                }


                if (banCo.DsOCo[chiSoCot, chiSoDong].QuanCoHienTai != null)
                {
                    if (banCo.DsOCo[chiSoCot, chiSoDong].QuanCoHienTai.PheMinh)
                    {
                        chiSoCotDaChon = chiSoCot;
                        chiSoDongDaChon = chiSoDong;
                        banCo.DsOCo[chiSoCotDaChon, chiSoDongDaChon].QuanCoHienTai.ChangeState();
                        foreach (var oco in banCo.DsOCo[chiSoCotDaChon, chiSoDongDaChon].QuanCoHienTai.NhungOCoTheDi(banCo, 
                            banCo.DsOCo[chiSoCotDaChon, chiSoDongDaChon],false))
                        {
                            oco.ChangeState();
                        }
                    }
                    
                }
                #endregion
            }
            ThayDoiTrenBanCo(null, null);
            
        }

        public void MainWindow_DiChuyenTrenBanCo(object sender, EventArgs e)
        {
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (ipServer != "")
            {
                if (dangTrongTranDau)
                {
                    if (MessageBox.Show(this, "Trận đấu chưa kết thúc bạn có chắc chắn muốn thoát!", "Chú ý!",
                        MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    {
                        quanLiKetNoi.ChapNhanThuaCuoc();
                        quanLiKetNoi.DongKetNoi();
                    }
                    else
                    {
                        e.Cancel = true;
                    }
                }
                else
                {
                    if (MessageBox.Show(this, "Bạn có chéc sẽ thoát!", "Chú ý!",
                        MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    {
                        if (quanLiKetNoi != null)
                        {
                            quanLiKetNoi.DongKetNoi();
                        }

                    }
                    else
                    {
                        e.Cancel = true;
                    }
                }
            }
            
        }

        public string findIPServer()
        {
            
            TcpClient tcpClient;
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                localIP = ip.ToString();
                try
                {
                    tcpClient = new TcpClient();
                    tcpClient.Connect(IPAddress.Parse(localIP), 8000);
                    NetworkStream stream = tcpClient.GetStream();
                    BinaryReader reader = new BinaryReader(stream);
                    BinaryWriter writer = new BinaryWriter(stream);
                    writer.Write("KiemTra");
                    try
                    {
                        if (reader.ReadString() == "OK")
                        {
                            return localIP;
                        }
                    }
                    catch (IOException e)
                    {
                        MessageBox.Show(this, e.Message);
                    }
                }
                catch (Exception exception)
                {
                }
                    
            }
            return "";
        }
    }
}
